package com.haoshuang.zhouzhoubang.ui.page.shop.confirm

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import androidx.recyclerview.widget.LinearLayoutManager
import com.alipay.sdk.app.PayTask
import com.gyf.immersionbar.ktx.immersionBar
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.config.Config
import com.haoshuang.zhouzhoubang.databinding.ActivityOrderQrBinding
import com.haoshuang.zhouzhoubang.model.bean.AddressBean
import com.haoshuang.zhouzhoubang.model.bean.OrderShopBean
import com.haoshuang.zhouzhoubang.ui.dialog.ChoosePlatformBenefitsDialog
import com.haoshuang.zhouzhoubang.ui.page.shop.address.AddressManagementActivity2
import com.haoshuang.zhouzhoubang.utils.Event
import com.haoshuang.zhouzhoubang.utils.PayResult
import com.haoshuang.zhouzhoubang.utils.PaymentUtil
import com.haoshuang.zhouzhoubang.utils.PreferenceUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lnkj.jialubao.utils.*
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.ktx.getString
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.visible
import com.mufeng.libs.utils.view.visibleOrGone
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.math.BigDecimal


/**
 *
 */
class OrderQrActivity : BaseVMActivity<OrderQrViewModel, ActivityOrderQrBinding>() {

    override fun initView(savedInstanceState: Bundle?) {
        binding.appBar.leftImageView().click { finish() }
        binding.appBar.title = "订单确认"
    }

    private var welfareItemBean: OrderShopBean.WelfareItemBean? = null
    private var productId = ""
    private var orderType: Int = 0
    private var orderBean: OrderShopBean? = null
    var list = arrayListOf<OrderShopBean.CartInfo>()
    lateinit var adapter: ShopAdapter
    var pay_type = 1
    var orderKey = ""

    // 规格id
    private var specId = ""

    // 数量
    private var num = 1

    // 配送类型 1: 快递 2: 自提
    private var deliveryType = 1

    private val SDK_PAY_FLAG = 1

    @SuppressLint("HandlerLeak")
    var mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    val payResult = PayResult(msg.obj as Map<String?, String?>)

                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo = payResult.result // 同步返回需要验证的信息
                    val resultStatus = payResult.resultStatus
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        toast("支付成功")
//                         startPage<SuccessActivity>()
                        finish()
                    } else {
                        toast("支付失败")

                    }
                }

                else -> {}
            }
        }
    }

    override fun initData() {
        EventBus.getDefault().register(this)



        orderType = intent.getIntExtra("orderType", 0)

        if (orderType == 0) {
            specId = intent.getString("specId")
            num = intent.getIntExtra("num", 1)
            productId = intent.getString("productId")
            vm.getData(
                "productId" to productId,
                "product_attr_unique" to specId,
                "cart_num" to num,
                "is_channel" to 3
            )
        } else {
            productId = intent.getString("productId")
            vm.getData3("cartId" to productId)
        }

        binding.llPlatformBenefits.visibleOrGone(orderType == 0)
        binding.tvChoosePlatformBenefits.clickWithTrigger {
            // 点击选择福利
            XPopup.Builder(mActivity)
                .isDestroyOnDismiss(true)
                .asCustom(ChoosePlatformBenefitsDialog(mActivity, orderBean?.welfare){
                    if (it != null){
                        welfareItemBean = it
                        binding.tvChoosePlatformBenefits.text = it.welfare_name
                    }
                })
                .show()
        }

        binding.radioGroup.setOnCheckedChangeListener { radioGroup, id ->
            when (id) {
                R.id.rbExpress -> {
                    // 快递
                    deliveryType = 1
                    binding.tvSelfPickupAddress.gone()
                    binding.tvAdr2.visible()
                    binding.llPostage.visible()
                    binding.allPrice.text = orderBean?.priceGroup?.allPrice
                }

                R.id.rbSelfPickup -> {
                    // 自提
                    deliveryType = 2
                    binding.tvSelfPickupAddress.visible()
                    binding.tvAdr2.gone()
                    binding.llPostage.gone()
                    // 合计金额等于总价减去运费
                    val allPrice = orderBean?.priceGroup?.allPrice?.toBigDecimal()
                    val goodsPostage = orderBean?.priceGroup?.goodsPostage?.toBigDecimal()
                    binding.allPrice.text =
                        allPrice?.subtract(goodsPostage!!)?.setScale(2, BigDecimal.ROUND_FLOOR)
                            ?.toString()
                }
            }
        }

        adapter = ShopAdapter(list)
        binding.apply {
            rvList.layoutManager = LinearLayoutManager(this@OrderQrActivity)
            rvList.adapter = adapter
            tvAdr2.clickWithTrigger {
                val intent = Intent(this@OrderQrActivity, AddressManagementActivity2::class.java)
                startActivityForResult(intent, 11)

            }
            llWx.clickWithTrigger {
                ivWx.setImageResource(R.mipmap.dz_ok)
                ivZfb.setImageResource(R.mipmap.dz_wx)
                pay_type = 1
            }
            llZfb.clickWithTrigger {
                ivWx.setImageResource(R.mipmap.dz_wx)
                ivZfb.setImageResource(R.mipmap.dz_ok)
                pay_type = 2
            }
            tvBz2.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {

                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

                }

                override fun afterTextChanged(s: Editable?) {
                    var num = tvBz2.text.toString().length
                    tvNum8.text = "${num}/200"
                }

            })

            tvButton.clickWithTrigger {
                var mark = tvBz2.text.toString()
                if (deliveryType == 1 && addressId.isNullOrBlank()) {
                    toast("收货地址不能为空")
                    return@clickWithTrigger
                }
                if (orderType == 0) {
                    if (pay_type == 1) {
                        vm.getData33New(
                            "key" to orderKey,
                            "payType" to pay_type,
                            "addressId" to addressId,
                            "delivery_method" to deliveryType,
                            "mark" to mark,
                            "is_channel" to 3,
                            "is_use_balance" to 0, // 不使用余额
                            "productId" to productId, // 商品id
                            "total_num" to num, // 购买数量
                            "product_attr_unique" to specId,// 商品规格参数
                            "welfare_id" to if (welfareItemBean == null || welfareItemBean?.id == -1) "" else welfareItemBean?.id
                        )
                    } else {
                        vm.getData2New(
                            "key" to orderKey,
                            "payType" to pay_type,
                            "addressId" to addressId,
                            "delivery_method" to deliveryType,
                            "mark" to mark,
                            "is_channel" to 3,
                            "is_use_balance" to 0, // 不使用余额
                            "productId" to productId, // 商品id
                            "total_num" to num, // 购买数量
                            "product_attr_unique" to specId,// 商品规格参数
                            "welfare_id" to if (welfareItemBean == null || welfareItemBean?.id == -1) "" else welfareItemBean?.id
                        )
                    }
                } else {
                    if (pay_type == 1) {
                        vm.getData33(
                            "key" to orderKey,
                            "payType" to pay_type,
                            "addressId" to addressId,
                            "delivery_method" to deliveryType,
                            "mark" to mark,
                            "is_channel" to 3
                        )
                    } else {
                        vm.getData2(
                            "key" to orderKey,
                            "payType" to pay_type,
                            "addressId" to addressId,
                            "delivery_method" to deliveryType,
                            "mark" to mark,
                            "is_channel" to 3
                        )
                    }
                }
            }
        }
    }

    var addressId = ""
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 11) {
            if (data != null) {
                var bean = data.getSerializableExtra("bean") as AddressBean
                binding.tvAdr.text = bean.city + bean.district + bean.detail
                binding.tvName.text = "${bean.real_name}     ${bean.phone}"
                addressId = bean.id.toString()
            }
        }
    }

    fun payAlipay(mContext: Context?, orderNo: String) {
        val payRunnable = Runnable {
            val alipay = PayTask(mContext as Activity?)
            val result = alipay.payV2(orderNo, true)
            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }
        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }

    //订阅方法，当接收到事件的时候，会调用该方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageEvent: Event) {
        if (messageEvent.code == 8003) {
            toast("支付成功")
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun startObserve() {
        vm.getData2New.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                if (!it?.body.isNullOrEmpty()) {
                    payAlipay(this@OrderQrActivity, it?.body!!)
                }else{
                    toast("福利兑换成功")
                    finish()
                }
            }
        }
        vm.getData33New.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                if (!it?.appId.isNullOrEmpty()) {
                    var api = WXAPIFactory.createWXAPI(this@OrderQrActivity, Config.WX_ID, false)
                    PreferenceUtils.putString("Wxpay", "0")
                    PaymentUtil.payWxPayment(api, it)
                }else{
                    toast("福利兑换成功")
                    finish()
                }
            }
        }
        vm.getData2.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                payAlipay(this@OrderQrActivity, it?.body!!)
            }
        }
        vm.getData33.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                var api = WXAPIFactory.createWXAPI(this@OrderQrActivity, Config.WX_ID, false)
                PreferenceUtils.putString("Wxpay", "0")
                PaymentUtil.payWxPayment(api, it)
            }
        }
        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if (code != "402") {
                    toast(msg)
                }
            }
            onSuccess {
                dismissLoading()
                orderBean = it
                if (it != null) {
                    list.clear()
                    list.addAll(it.cartInfo)
                    adapter.notifyDataSetChanged()
                    binding.apply {
                        if (!it.userAddress.phone.isNullOrBlank()) {
                            tvAdr.text =
                                it.userAddress.city + it.userAddress.district + it.userAddress.detail
                            tvName.text = "${it.userAddress.real_name}     ${it.userAddress.phone}"
                        }
                        goodsPostage.text = "¥" + it.priceGroup.goodsPostage
                        totalPrice.text = "¥" + it.priceGroup.totalPrice
                        allPrice.text = it.priceGroup.allPrice

                        orderKey = it.orderKey?:""
                        addressId = it.userAddress.id.toString()
                        tvSelfPickupAddress.text = it.pickup_address
                        tvChoosePlatformBenefits.text = if (it.welfare == null || it.welfare?.can_use.isNullOrEmpty()) "暂无福利" else ""
                        tvChoosePlatformBenefits.isEnabled = it.welfare != null && !it.welfare.can_use.isNullOrEmpty()
                    }
                }
            }
        }
        vm.getData3.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if (code != "402") {
                    toast(msg)
                }
            }
            onSuccess {
                dismissLoading()
                orderBean = it
                if (it != null) {
                    list.clear()
                    list.addAll(it.cartInfo)
                    adapter.notifyDataSetChanged()
                    binding.apply {
                        tvAdr.text = it.userAddress.detail
                        goodsPostage.text = "¥" + it.priceGroup.goodsPostage
                        totalPrice.text = "¥" + it.priceGroup.totalPrice
                        allPrice.text = it.priceGroup.allPrice
                        if (!it.userAddress.real_name.isNullOrBlank())
                            tvName.text = "${it.userAddress.real_name}     ${it.userAddress.phone}"
                        orderKey = it.orderKey?:""
                        addressId = it.userAddress.id.toString()
                        tvSelfPickupAddress.text = it.pickup_address
                    }
                }
            }
        }
    }

    override fun initImmersionBar() {
        immersionBar {
            statusBarDarkFont(false)
            transparentStatusBar()
            titleBarMarginTop(binding.appBar)
        }
    }

}